#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const inquirer = require('inquirer')
const ejs = require('ejs')

inquirer.prompt([
    {
      type: 'input',
      name: 'name',
      message: 'Project name?'
    },
    {
      type: 'input',
      name: 'version',
      default: '1.0.0',
      message: 'Version?'
    },
])
.then(answer => {
    console.log('answer :>> ', answer);
    // 根据用户回答的结果生成文件
    // 模板目录
    const templateDir = path.join(__dirname, 'template')
    // 目标目录
    const destDir = process.cwd()
    // 将模板下的文件全部转换到目标目录
    const walkSync = function (currentDirPath, callback) {
        fs.readdirSync(currentDirPath).forEach(function (file) {
            const filePath = path.join(currentDirPath, file);
            const stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, file);
            } else if (stat.isDirectory()) {
                fs.mkdirSync(path.join(destDir, filePath.replace(templateDir, '')))
                walkSync(filePath, callback);
            }
        });
    }
    walkSync(templateDir, function(filePath, file) {
        if (file === 'package.json') {
            ejs.renderFile(path.join(templateDir, file), answer, (err, result) => {
                if (err) throw err
                // 将结果写入目标文件路径
                fs.writeFileSync(path.join(destDir, file), result)
                const exec = require('child_process').exec;
                const cmd = 'npm i --save';
                console.log('正在进行包安装==========>>>');
                exec(cmd, function(error, stdout, stderr) {
                    console.log(error, stdout, stderr);
                });
            })
        }else {
            const readable=fs.createReadStream(filePath);//创建读取流
            const writable=fs.createWriteStream(path.join(destDir, filePath.replace(templateDir, '')));//创建写入流
            readable.pipe(writable);
        }
    });
})
/* 未进行try/catch的处理，必须可读性error的输出 */